package cn.virens.web.components.open.oauth;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Component;

import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;

@Component
public class Oauth2ServiceImpl implements Oauth2Service {
	private final static ThreadLocal<String> REQUEST_CHOSE = new ThreadLocal<String>();

	private final Map<String, AuthRequest> requestMap = new ConcurrentHashMap<>();

	@Override
	public void addAuthRequest(String type, AuthRequest request) {
		this.requestMap.put(type, request);
	}

	@Override
	public void removeAuthRequest(String type) {
		this.requestMap.remove(type);
	}

	@Override
	public AuthRequest request() {
		if (requestMap.size() == 1) {
			return requestMap.values().iterator().next();
		} else {
			return requestMap.get(REQUEST_CHOSE.get());
		}
	}

	@Override
	public String getType() {
		return REQUEST_CHOSE.get();
	}

	@Override
	public boolean switchover(String type) {
		if (requestMap.containsKey(type)) {
			REQUEST_CHOSE.set(type);
		} else {
			return false;
		}

		return true;
	}

	@Override
	public String authorize(String state) {
		return request().authorize(state);
	}

	@Override
	@SuppressWarnings("unchecked")
	public AuthResponse<AuthUser> loign(AuthCallback authCallback) {
		return request().login(authCallback);
	}

}
